package com.carp.shard.plugin;


import com.alibaba.druid.DbType;
import com.alibaba.druid.util.JdbcConstants;
import com.alibaba.fastjson.JSON;
import com.carp.shard.plugin.processor.ShardProcessor;
import com.carp.shard.plugin.utils.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.springframework.stereotype.Component;

import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.text.DateFormat;
import java.util.*;
import java.util.regex.Matcher;

/**
 * 分片插件
 *
 * @author lile
 * @since 2024/4/29
 */
@Slf4j
@Component
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class ShardPlugin implements Interceptor {

    /**
     * 数据库类型
     */
    public static final DbType DB_TYPE = JdbcConstants.MYSQL;

    /**
     * 插件主流程
     */
    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        Object target = invocation.getTarget();
        target = realTarget(target);
        MetaObject metaObject = SystemMetaObject.forObject(target);
        BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql");
        Object parameterObject = boundSql.getParameterObject();

        if (Objects.isNull(parameterObject)) {
            return invocation.proceed();
        }

        try {
            MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
            SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();

            if (sqlCommandType == SqlCommandType.SELECT) {
                processRead(metaObject);
            } else if (Arrays.asList(SqlCommandType.INSERT, SqlCommandType.UPDATE, SqlCommandType.DELETE).contains(sqlCommandType)) {
                processWrite(metaObject, invocation);
            }
        } catch (Exception e) {
            // 捕获插件所有异常，异常时降级为原流程，避免影响正常流程
            log.error("[shard-plugin] ERROR", e);
        }
        log.info("[shard-plugin] sql: {} \n  parameterObject({}): {}", CommonUtils.removeBreakingWhitespace(boundSql.getSql()), parameterObject.getClass().getSimpleName(), JSON.toJSONString(parameterObject));
        return invocation.proceed();
    }

    /**
     * 获得真正的处理对象,可能多层代理
     */
    @SuppressWarnings("unchecked")
    private <T> T realTarget(Object target) {
        if (Proxy.isProxyClass(target.getClass())) {
            MetaObject metaObject = SystemMetaObject.forObject(target);
            return realTarget(metaObject.getValue("h.target"));
        }
        return (T) target;
    }

    /**
     * 处理读请求
     */
    private void processRead(MetaObject metaObject) {
        ShardProcessor shardProcessor = new ShardProcessor(metaObject);
        shardProcessor.route();
    }

    /**
     * 处理写请求
     */
    private void processWrite(MetaObject metaObject, Invocation invocation) {
        ShardProcessor shardProcessor = new ShardProcessor(metaObject);
        shardProcessor.processParams();
        shardProcessor.processWrite((Connection) invocation.getArgs()[0]);
    }

    @Override
    public Object plugin(Object target) {
        if (target instanceof StatementHandler) {
            return Plugin.wrap(target, this);
        }
        return target;
    }

    @Override
    public void setProperties(Properties properties) {
        // do nothing
    }

    public static String showSql(Configuration configuration, BoundSql boundSql) {
        // 获取参数
        Object parameterObject = boundSql.getParameterObject();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        // sql语句中多个空格都用一个空格代替
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
        if (CollectionUtils.isNotEmpty(parameterMappings) && parameterObject != null) {
            // 获取类型处理器注册器，类型处理器的功能是进行java类型和数据库类型的转换
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            // 如果根据parameterObject.getClass(）可以找到对应的类型，则替换
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                for (ParameterMapping parameterMapping : parameterMappings) {
                    sql = sql.replaceFirst("\\?",
                            Matcher.quoteReplacement(getParameterValue(parameterObject)));
                }
            } else {
                // MetaObject主要是封装了originalObject对象，提供了get和set的方法用于获取和设置originalObject的属性值,主要支持对JavaBean、Collection、Map三种类型对象的操作
                MetaObject metaObject = configuration.newMetaObject(parameterObject);
                Iterator<?> iterator = null;
                for (ParameterMapping parameterMapping : parameterMappings) {
                    String propertyName = parameterMapping.getProperty();
                    if (metaObject.hasGetter(propertyName)) {
                        Object obj = metaObject.getValue(propertyName);
                        if (obj instanceof List) {
                            if (iterator == null) {
                                iterator = ((List<?>) obj).iterator();
                            }
                            if (iterator.hasNext()) {
                                Object next = iterator.next();
                                sql = sql.replaceFirst("\\?",
                                        Matcher.quoteReplacement(getParameterValue(next)));
                            } else {
                                iterator = null;
                            }
                        } else {
                            sql = sql.replaceFirst("\\?",
                                    Matcher.quoteReplacement(getParameterValue(obj)));
                        }
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        // 该分支是动态sql
                        Object obj = boundSql.getAdditionalParameter(propertyName);
                        sql = sql.replaceFirst("\\?",
                                Matcher.quoteReplacement(getParameterValue(obj)));
                    } else {
                        // 打印出缺失，提醒该参数缺失并防止错位
                        sql = sql.replaceFirst("\\?", "缺失");
                    }
                }
            }
        }
        return sql;
    }

    /**
     * 获取参数值
     * 如果参数是String，则添加单引号；如果是日期，则转换为时间格式器并加单引号；对参数是null和不是null的情况作了处理
     */
    private static String getParameterValue(Object obj) {
        String value;
        if (obj instanceof String) {
            value = "'" + obj + "'";
        } else if (obj instanceof Date) {
            DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
            value = "'" + formatter.format(new Date()) + "'";
        } else {
            if (obj != null) {
                value = obj.toString();
            } else {
                value = "";
            }
        }
        return value;
    }

}
